package org.dromara.solonplugins.job;

import org.dromara.solonplugins.job.annotation.EnableJob;
import org.dromara.solonplugins.job.impl.DefaultJobCallback;
import org.dromara.solonplugins.job.impl.DefaultJobSource;
import org.dromara.solonplugins.job.impl.JobExecutor;
import org.noear.solon.Solon;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.Plugin;
import org.noear.solon.core.event.AppLoadEndEvent;

/**
 * Solon插件入口
 *
 * @author: aoshiguchen
 */
public class XPluginImp implements Plugin {

    @Override
    public void start(AppContext context) throws Throwable {
        EnableJob enableJob = Solon.app().source().getAnnotation(EnableJob.class);
        if (null == enableJob || !enableJob.value()) {
            return;
        }

        JobExecutor jobExecutor = new JobExecutor();
        jobExecutor.setJobSource(new DefaultJobSource());
        jobExecutor.setJobCallback(new DefaultJobCallback());
        context.wrapAndPut(JobExecutor.class, jobExecutor);
        context.wrapAndPut(IJobExecutor.class, jobExecutor);

        //应用加载完后，再启动任务
        Solon.app().onEvent(AppLoadEndEvent.class, e -> {
            IJobSource jobSource = context.getBean(IJobSource.class);
            IJobCallback jobCallback = context.getBean(IJobCallback.class);
            if (null != jobSource) {
                jobExecutor.setJobSource(jobSource);
            }
            if (null != jobCallback) {
                jobExecutor.setJobCallback(jobCallback);
            }
            jobExecutor.start();
        });
    }

}
